import javax.swing.*
import java.awt.*
import java.awt.event.*
import javax.swing.tree.*
import javax.swing.tree.DefaultMutableTreeNode as TreeNode
import net.miginfocom.swing.MigLayout

actions{
	action(id: "newAction",
			name: "Connect ...",
			mnemonic: "N",
			enabled: true,
			accelerator: shortcut("N"),
			closure: {
			    controller.newConfigGroup()
            })
	action(id: "maximizeAction",
			name: "Maximize",
			mnemonic: "M",
			enabled: false,
			accelerator: shortcut("M"),
			closure: {
			    //
            })
	action(id: "connectAction",
			name: "Connect",
			mnemonic: "C",
			enabled: bind {model.readyToConnect},
			accelerator: shortcut("C"),
			closure: {
			    controller.showConnect(
			    		group.selectedItem,connectionName.text
			    		)
            })
	action(id: "clearAction",
			name: "Clear",
			mnemonic: "X",
			enabled: bind {!model.empty},
			accelerator: shortcut("X"),
			closure: {
				if(model.activeConnectionTab &&
						!model.activeConnectionTab.model.connected) {
					model.activeConnectionTab.controller.clear()
				}
            })
	action(id:  "websiteAction",
			name:'Go To SSHiffon website',
			mnemonic: "W",
			accelerator: shortcut ("W"),
			closure:{
			  Desktop.getDesktop().browse(new URI('http://code.google.com/p/sshiffon/'))
			})
	action(id: "aboutAction",
			name:'About SSHiffon',
			mnemonic: "A",
			accelerator: shortcut ("A"),
			closure:{
	    optionPane(message:"SSHiffon v"+app.applicationProperties."app.version"+"\n\nSSHiffon is an SSH Terminal, Tunneler, and SFTP Client, with nice bits.\n")
	    .createDialog('About SSHiffon')
	    .show()
		})
	action(id: 'addGroupAction', 
				name: 'Add Group', 
				closure: {
                        	def groupName= JOptionPane.showInputDialog("Group name")
                        	if(groupName!=null )
                        	{
                        		controller.addGroup(groupName)
                        	}
                        })
	action(id: 'deleteAction', 
			name:'Delete',
			mnemonic: "D",
			enabled: bind {model.connectionSelected},
			accelerator: shortcut ("D"),
			closure: {
                TreePath[] paths = savedConnections.getSelectionPaths()
                paths.each({ path ->
                    if(path != null)
                    {
                        controller.delete(path.getPath())
                    }
                })
			})
/*    action(id: "connectShortcutAction",
    		name:'Connect',
			enabled: bind {model.connectionSelected},
			closure: connectAction.closure
    	) */
	action(id: "quitAction",
			name: "Quit",
			mnemonic: "Q",
			accelerator: shortcut("Q"),
			closure: controller.quit)

			
	action(id: "terminalAction",
			mnemonic: "T",
			name: "Terminal",
			//enabled: bind { model.state.connected && !model.state.terminalActive},
			enabled: false,
			accelerator: shortcut("T"),
			closure: {
				model.activeConnectionTab.model.connectedGroup.view.terminalAction.closure()
		})
    action(id: "sftpAction",
			mnemonic: "F",
			name: "File Manager",
			//enabled: bind { model.state.connected && !model.state.sftpActive },
			enabled: false,
			accelerator: shortcut("F"),
			closure: {
				model.activeConnectionTab.model.connectedGroup.view.sftpAction.closure()
            })
	action(id: "configAction",
			name: "Config",
			mnemonic: "C",
			//enabled: bind { model.state.connected && !model.state.configActive },
			enabled: false,
			accelerator: shortcut("O"),
			closure: {
				model.activeConnectionTab.model.connectedGroup.view.configAction.closure()
            })
    action(id: "disconnectAction",
			name: "Close",
    		enabled: bind { model.activeConnectionTab!=null },
			//mnemonic: "D",
			closure: controller.closeAction)            
}

application(title:'SSHiffon',
  id: 'sshiffon',
  size:[900,700],
//  pack:true,
  //location:[50,50],
  locationByPlatform:true,
  iconImage: imageIcon('/griffon-icon-48x48.png').image,
  iconImages: [imageIcon('/griffon-icon-48x48.png').image,
               imageIcon('/griffon-icon-32x32.png').image,
               imageIcon('/griffon-icon-16x16.png').image],
  layout:new MigLayout("fill, insets 0")
) {

    menuBar()
    {
        menu('File',mnemonic:'F')
           {
            menuItem ( newAction )
            separator ()
            menuItem ( quitAction )
        }
        menu('Window',mnemonic:'W',enabled:false)
        {
        }
        menu(text:'Help', mnemonic:'H') {
        	menuItem ( websiteAction )
        	separator()
            menuItem ( aboutAction )
        }
    }
    toolBar(constraints:'north')
	{
    	button(action: newAction, icon: imageIcon('/crystal24/connect_no.png'), toolTipText: 'New')
    	//button(action: maximizeAction, icon: imageIcon('/maximize-24x24.png'), toolTipText: 'Maximize')
    	separator ()
    	button(action: terminalAction, icon: imageIcon('/crystal24/terminal.png'), toolTipText: 'Terminal')
    	button(action: sftpAction, icon: imageIcon('/crystal24/folder.png'), toolTipText: 'SFTP')
    	button(action: configAction, icon: imageIcon('/crystal24/utilities.png'), toolTipText: 'Config')
    	separator()
    	button(action: disconnectAction, icon: imageIcon('/crystal24/exit.png'), toolTipText: 'Disconnect')
	}
    
    
    panel(constraints:"grow",layout:new MigLayout("fill"),id:'sshiffonMainPanel') {
    	tabbedPane(constraints: "grow", id: 'mainTabbedPane', tabPlacement: JTabbedPane.TOP, font: sshiffonMainPanel.font.deriveFont(15.0f),
        		stateChanged: { evt ->
        			controller.activeConnectionChanged(mainTabbedPane.selectedIndex)
        }) {
    		//tabs here ...
    	}.addKeyListener( { evt ->
                            if(mainTabbedPane.getSelectedIndex()>0)
                            {
                                int keyCode = evt.getKeyCode();
                                String keyText = KeyEvent.getKeyText(keyCode);
                                if(keyCode > 30 && keyCode < 127 && evt.getID()==KeyEvent.KEY_RELEASED)
                                {
                                    // send character & focus to terminal
                                    logger.info('TODO: main tabbedPane attempting to send character to terminal ..')
                                    controller.activateTerm(mainTabbedPane.getSelectedIndex(),keyCode)
                                }
                            }
                } as java.awt.event.KeyListener )
    scrollPane(constraints:"south, h 100") {
        panel(layout: new MigLayout("fill, insets 0"))
        {
           table(id:'statusBar',constraints:"grow, gap 0")
           
           // button(action:action(name:'show/hide',closure:{ if(statusBar.height>0) {statusBar.height=0} else {statusBar.height=100} }))
        }
    }
    }
}

def popupMenu=  popupMenu()
{
	menuItem( terminalAction )
	separator()
	menuItem( sftpAction )
	menuItem( configAction )
	separator()
	menuItem( disconnectAction )
}
mainTabbedPane.addMouseListener({ e -> if (e.isPopupTrigger()) { popupMenu.show(e.getComponent(), e.getX(), e.getY());} } as java.awt.event.MouseAdapter)


controller.newConfigGroup()
//controller.refreshConnectionsView()
controller.setLoggerPanel()

